<template>
  <view class="facial-verification-page">
    <view class="body">
      <view class="title">
        <text>人脸核身</text>
      </view>
      <view v-if="show">
        <view class="camera-cover">
          <camera device-position="front" flash="off" style="width: 700rpx;height: 700rpx"/>
        </view>
        <view class="camera-tip">{{ tipsText|| '未检测到摄像头，请检查摄像头是否开启' }}</view>
        <view class="btn" style="margin-top: 100rpx">
          <u-button type="primary" color="#FF7947" @click="takePhoto" :disabled="!canTakePhoto">拍照</u-button>
        </view>
      </view>
      <view v-if="src">预览</view>
      <image mode="widthFix" :src="src"></image>
    </view>


  </view>
</template>

<script>


import {uploadImg} from "@/api/common";
import {authentication, memberDetail} from "@/api/manager/order";

export default {
  name: "facial-verification",
  data() {
    return {
      show: true,
      src: '',
      user: {
        memberId: null,
        idName: '',
        idNumber: '',
        facePhoto: ''
      },
      token: null,
      imgSrc: "",
      result: "",

      cameraEngine: undefined,
      //可拍照状态
      canTakePhoto: false,
      tipsText: '',
    }
  },
  onLoad(options) {
    const memberId = options.memberId
    this.user.memberId = memberId
    this.getMemberDetail(memberId)
    this.initData()
  },
  methods: {
    //初始化相机
    initData(){
      let that = this
      //初始化人脸识别
      uni.initFaceDetect();
      // 2、创建 camera 上下文 CameraContext 对象
      that.cameraEngine = uni.createCameraContext();
      // 3、监听 camera 实时帧数据
      const listener = that.cameraEngine.onCameraFrame((frame) => {
        // 4、人脸识别，使用前需要通过 wx.initFaceDetect 进行一次初始化，推荐使用相机接口返回的帧数据
        uni.faceDetect({
          frameBuffer: frame.data,
          width: frame.width,
          height: frame.height,
          enablePoint: true,
          enableConf: true,
          enableAngle: true,
          enableMultiFace: true,
          success: faceData => {
            let face = faceData.faceInfo[0];
            //人脸位置校验
            var centerWidth = 150;
            var centerHeight = 150;

            if (faceData.x == -1 || faceData.y == -1) {
              that.canTakePhoto = false;
              that.tipsText = '检测不到人';
            }

            if (faceData.faceInfo.length > 1) {
              that.canTakePhoto = false;
              that.tipsText = '请保证只有一个人';
            } else {
              const { pitch, roll, yaw } = face.angleArray;
              const standard = 0.3;

              if (Math.abs(pitch) >= standard || Math.abs(roll) >= standard || Math.abs(yaw) >= standard) {
                that.canTakePhoto = false;
                that.tipsText = '请平视摄像头';
              } else if (
                  face.x < (frame.width - centerWidth) / 2 ||
                  face.x > (frame.width - centerWidth) / 2 + centerWidth ||
                  face.y < (frame.height - centerHeight) / 2 ||
                  face.y > (frame.height - centerHeight) / 2 + centerHeight
              ) {
                that.canTakePhoto = false;
                this.tipsText = '请将人脸对准中心位置';
              } else if (
                  face.confArray.global <= 0.8 ||
                  face.confArray.leftEye <= 0.8 ||
                  face.confArray.mouth <= 0.8 ||
                  face.confArray.nose <= 0.8 ||
                  face.confArray.rightEye <= 0.8
              ) {
                that.canTakePhoto = false;
                that.tipsText = '请勿遮挡五官';
              } else {
                // listener.stop();
                that.canTakePhoto = true;
                that.tipsText = '即将拍照，请保持！';
                setTimeout(function() {
                  // that.handleTakePhotoClick();
                }, 3000);
                return;
                let time = 3;
                that.tipsText = time + '秒后拍照，请保持！';
                let timer3 = setInterval(function() {
                  time--;
                  if (time <= 0) {
                    clearInterval(timer3);
                    // 拍照
                    return that.handleTakePhotoClick();
                  } else {
                    that.tipsText = time + '秒后拍照，请保持！';
                  }
                }, 1000);
              }
            }
          },
          fail: err => {
            if (err.x == -1 || err.y == -1) {
              that.tipsText = '检测不到人';
            } else {
              that.tipsText = err.errMsg || '网络错误，请退出页面重试';
            }
          }
        });
      })

      // 5、开始监听帧数据
      listener.start();

    },
    takePhoto() {
      const ctx = uni.createCameraContext();
      ctx.takePhoto({
        quality: 'high',
        success: (res) => {
          this.src = res.tempImagePath
          this.show = false
          uploadImg(res.tempImagePath).then(res => {
            if (res.url) {
              this.user.facePhoto = res.url
              // 提交认证
              authentication(this.user).then(res => {
                this.$modal.msgSuccess(res.data)
              }).catch(err => {
                this.$modal.msgError(err.data)
              }).finally(() => {
                setTimeout(() => {
                  this.$tab.navigateBack()
                }, 500)
              })
            }
          })
        }
      });
    },
    getMemberDetail(memberId) {
      memberDetail(memberId).then(res => {
        this.user = res.data
      })
    }
  }

}
</script>


<style scoped lang="scss">
.facial-verification-page {
  .body {
    margin: 20rpx;
    padding: 20rpx;
    border-radius: 8rpx;
    background-color: #fff;

    .title {
      margin-bottom: 10rpx;
      font-size: 32rpx;
      font-weight: bold;
    }

    .form {
      .form-btns {
        margin-top: 20rpx;
      }
    }

    .camera-cover {
      border-radius: 50%;
      overflow: hidden;
      border-color: #fff;
      text-align: center;
      display: flex;
      justify-content: center;
      position: relative;
    }

    .camera-tip{
      padding: 10rpx 0;
      text-align:center;
    }
  }

}

</style>
